import axios from "axios";
import { getToken, removeToken } from "@/utils";
import router from "@/router"

const request = axios.create({
    baseURL: 'http://geek.itheima.net/v1_0',
    timeout: 5000
})

request.interceptors.request.use((config) => {
    const token = getToken()
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

// 响应拦截器，在响应返回到客户端之前，做拦截，重点处理返回的数据
request.interceptors.response.use((response) => {
    // 2xx 范围内的状态码都会触发改函数
    return response.data
}, (error) => {
    // 超出 2xx 范围的状态码都会触发该函数
    // 监控401 token失效
    console.dir("error", error)
    if (error?.response?.status === 401) {
        removeToken()
        router.navigate("/login")
        window.location.reload()
    }
    return Promise.reject(error)
})
export { request }